Packages and Interfaces
In this module you will learn…..
· Introduction
·
CLASSPATH
variable
·
Creating a
Package
·
Access
protection through packages
Introduction to Packages
In a large programming environment it is possible to run out of unique names for classes. There are also chances that two or more persons in the same place use the same names for their classes thus ending up in chaos. Java provides a way to avoid this through packages.
Packages are nothing but the collection of classes and interfaces that provide a high degree of access protection and name space management. For example, java.io package contain classes and interfaces for managing various I/O operations.
One of the main uses of packages is to provide access modification. It provides a high degree of interaction & interdependency within a package and reduces interaction across packages.
CLASSPATH variable
Whenever a class is created without any package, it is added to the default package. Hence, any class is a part of some package. Java Compiler and Interpreter searches for class files in the path specified in the CLASSPATH environment variable. When creating a package ensure that the root directory of the package is included in the CLASSPATH variable.
Creating a
Package
· Create a directory that has the same name as that of the package.
· Include a package statement along with the name as the first statement in the program. Example: package mypack;
· Write all the class definitions and compile as usual.
· To run the program, there are two ways, one - change the current directory to a level one up the hierarchy, run or change the CLASSPATH variable accordingly. A simple package example follows.
Example
package StudentPack;
class Student
{
String name;
int roll_no;
int
marks[]=new int[3];
Student(String n,int r,int arr[])
{
name=n;
roll_no=r;
for(int
i=0;i<3;i++)
{
marks[i]=arr[i];
}
}
void
getResult()
{
int
total=marks[0]+marks[1]+marks[2];
float
avg=total/3;
System.out.println("Name of the student : "+name);
System.out.println("Total marks secured : "+total);
System.out.println("
Average : "+avg);
}
}
class PackDemo
{
public
static void main(String args[])
{
int arr[]=new
int[3];
arr[0]=56;
arr[1]=67;
arr[2]=78;
Student
std1=new Student("Rahul",03,arr);
std1.getResult();
}
}
Access
protection through packages
As said earlier, packages provide a high level of security both within and across the package. Few members can be made available even for the package, i.e., for all the classes within a package, and few can be made available even for those subclasses present in the other package. These are certain levels of security using package.
1. Same package subclass
2. Same package non subclass
3. Different package subclass
4. Different package non subclass
The entire access rule is illustrated in the following table:
|
|
Private |
No
modifier |
Protected |
Public |
|
Same Class |
Yes |
yes |
yes |
yes |
|
Same package Subclass |
No |
yes |
yes |
yes |
|
Same package Non Subclass |
No |
yes |
yes |
yes |
|
Different package Subclass |
No |
no |
yes |
yes |
|
Different package NonSubclass |
No |
no |
no |
yes |
The following example completely explains the above table.
Example
package MyPack1;
public class BaseClass
{
private int
pri_i=10;
protected
int prot_i=20;
public int
pub_i=30;
int no_i=40;
public
BaseClass( )
{
System.out.println("Super class constructor");
System.out.println( );
System.out.println("
private value of i : "+pri_i);
System.out.println("
protected value of i : "+prot_i);
System.out.println("
public value of i : "+pub_i);
System.out.println("No specifier value of i : "+no_i);
}
}
class DerivedClass extends BaseClass
{
DerivedClass()
{
System.out.println("Derived class constructor");
System.out.println( );
//System.out.println("
private value of i : "+pri_i); //same class only
System.out.println("
protected value of i : "+prot_i);
System.out.println("
public value of i : "+pub_i);
System.out.println("No specifier value of i : "+no_i);
}
}
class SamePackage
{
SamePackage(
)
{
System.out.println("Same Package nonsub class constructor");
System.out.println();
//System.out.println("
private value of i : "+pri_i); //same class only
System.out.println("
protected value of i : "+prot_i);
System.out.println("
public value of i : "+pub_i);
System.out.println("No specifier value of i : "+no_i);
}
}
package MyPack1;
public class AccessDemo
{
public
static void main(String args[])
{
BaseClass
bc=new BaseClass( );
DerivedClass dc=new DerivedClass( );
SamePackage
sp=new SamePackage( );
}
}
package MyPack2;
class DerivedClass1 extends BaseClass
{
DerivedClass1( )
{
System.out.println("Derived class other package constructor");
System.out.println( );
//System.out.println("
private value of i : "+pri_i); //same class only
System.out.println("
protected value of i : "+prot_i);
System.out.println("
public value of i : "+pub_i);
//System.out.println("No specifier value of i : "+no_i);
//same package
}
}
class OtherPackage
{
OtherPackage( )
{
System.out.println("Same Package nonsub class constructor");
System.out.println();
//System.out.println("
private value of i : "+pri_i); //same class only
//System.out.println("
protected value of i : "+prot_i);//derived classes only
System.out.println("
public value of i : "+pub_i);
//System.out.println("No specifier value of i : "+no_i);
//same package
}
}
class AccessDemo
{
public
static void main(String args[])
{
DerivedClass1 dc=new DerivedClass1( );
OtherPackage op=new OtherPackage( );
}
}
}
If you have worked with C / C++ programs, the first line of your program would be #include statements. In Java, this is achieved through the import statement. Until now, by default you were importing the java.lang package, whether you have an import statement or not. If you want to use any other utilities that are not present in java.lang it is mandatory for you to explicitly specify the import statement within your program so that the required packages and classes are available for you to work with.
Example: import java.applet.*;
// * says to import all the classes of
that package
import Java.awt.*;
In the same way it is also possible to import packages defined by the user. This is achieved by simply writing the import statement along with the package name.
Example: import Mypack.*;
Up in the hierarchy comes
the package statement, then import and later the class definitions.
Object-oriented programming is also concerned with communication between objects. In this context, interfaces in Java provide a set of abstract methods, i.e., method-less implementation. An interface specifies what can you talk to an object, but specifies nothing about how and what kind of objects will handle your messages.
Therefore, an interface is a collection of abstract behavior that individual classes implementing them should handle. It is very similar to class but does not contain instance variables (but it can have final variables) and their methods are declared without any body. An interface can be defined using the interface keyword. The general form of interface is shown below.
modifier
interface interfacename
{
return type method1(parameter list);
return type method2(parameter list);
.
.
.
type final
name = val ;
.
.
.
}
The main difference between abstract classes and interface is that abstract class can implement none, some or all its methods whereas an interface implements none of its methods. One more difference is that abstract classes are extended whereas interfaces are implemented. However, in both the cases objects cannot be instantiated. Merely having a interface is of no use. There should be a class that implements the interface. This is achieved using the keyword implements. The following example illustrates the above fact.
interface GeneralStack
{
void
push(int item);
int pop( );
}
class StaticStack implements GeneralStack
{
private int
stack[];
private int
top;
StaticStack(int size)
{
stack=new
int[size];
top=-1;
}
public void
push(int item)
{
if(top==stack.length-1)
System.out.println("Stack is full");
else
stack[++top]=item;
}
public int
pop()
{
if(top<0)
{
System.out.println("Stack is empty");
return 0;
}
else
return
stack[top--];
}
}
class StaticStackDemo
{
public
static void main(String args[])
{
StaticStack
stk=new StaticStack(5);
for(int
i=0;i<5;i++)
stk.push(i);
System.out.println("After popping ....");
for(int
i=0;i<5;i++)
System.out.println(stk.pop());
}
}
class DynamicStack implements GeneralStack
{
private int
stack[];
private int
top;
DynamicStack(int size)
{
stack=new
int[size];
top=-1;
}
public void
push(int item)
{
if(top==stack.length-1)
{
int
temp[]=new int[stack.length * 2];
for(int
i=0;i<stack.length;i++)
temp[i]=stack[i];
stack=temp;
stack[++top]=item;
}
else
stack[++top]=item;
}
public int
pop()
{
if(top<0)
{
System.out.println("Stack is empty");
return 0;
}
else
return
stack[top--];
}
}
class DynamicStackDemo
{
public
static void main(String args[])
{
DynamicStack stk=new DynamicStack(5);
for(int
i=0;i<10;i++)
stk.push(i);
System.out.println("After poping ....");
for(int
i=0;i<10;i++)
System.out.println(stk.pop());
}
}
Note
1. A class can both extend a parent class and can implement one or more interfaces. Example: Class A extends B implements int1, int2…
2. A class cannot extend more than one class (i.e. multiple inheritance is not possible) whereas a class can implement any number of interfaces, thus allowing multiple interface inheritance.
3. If a class implementing an interface does not implement all the methods, then the class must be declared abstract.
The following listing uses the above listing and also demonstrates Dynamic method Dispatch
Example
class DispatchDemo
{
public
static void main(String args[])
{
GeneralStack gstack;
StaticStack
sstack=new StaticStack(5);
DynamicStack dstack=new DynamicStack(5);
gstack=sstack;
for(int
i=0;i<5;i++) gstack.push(i);
gstack=dstack;
for(int
i=0;i<12;i++) gstack.push(i);
gstack=sstack;
System.out.println("Contents of static stack ...");
for(int
i=0;i<5;i++)
System.out.println(gstack.pop());
gstack=dstack;
System.out.println("Contents of Dynamic stack ...");
for(int
i=0;i<12;i++)
System.out.println(gstack.pop());
}
}
Summary
· Packages are nothing but the collection of classes and interfaces that provide a high degree of access protection and name space management.
· Object-oriented programming is also concerned with communication between objects. In this context, interfaces in Java provide a set of abstract methods, i.e., method-less implementation. An interface specifies what can you talk to an object, but specifies nothing about how and what kind of objects will handle your messages.
· An interface is a collection of abstract behavior that individual classes implementing them should handle. It is very similar to class but does not contain instance variables (but it can have final variables) and their methods are declared without any body.
Test your knowledge
1. Which of the following will compile without error
1)
import
java.awt.*;
package
Mypackage;
class
Myclass {}
2)
package
MyPackage;
import
java.awt.*;
class
MyClass{}
3)
/*This
is a comment */
package
MyPackage;
import
java.awt.*;
class
MyClass{}
2. You have these files in the same directory. What will happen when you attempt to compile and run Class1.java if you have not already compiled Base.java
//Base.java
package
Base;
class
Base
{
protected void amethod()
{
System.out.println("amethod");
}//End of amethod
}//End
of class base
package
Class1;
//Class1.java
public
class Class1 extends Base
{
public static void main(String
argv[])
{
Base b = new Base();
b.amethod();
}//End of main
}//End
of Class1
1)
Compile
Error: Methods in Base not found
2) Compile Error: Unable to access protected method in base class
3) Compilation followed by the output "amethod"
4)Compile error: Superclass Class1.Base of class Class1.Class1 not found
3. What happens when you
attempt to compile and run these two files in the same directory?
//File
P1.java
package
MyPackage;
class
P1{
void
afancymethod(){
System.out.println("What a fancy
method");
}
}
//File
P2.java
public
class P2 extends P1{
afancymethod();
}
1) Both compile and P2 outputs "What a fancy
method" when run
2) Neither will compile
3) Both compile but P2 has an error at run time
4) P1 compiles cleanly but P2 has an error at compile time
1.
Use
interface to develop stack use pop and push methods.
2. Create a package of above program and import in your program for push and pop.